<template>
  <div>
    <el-button type="success" @click="savePers()">保存权限</el-button>
    <el-tree
      :data="perlist"
      show-checkbox
      node-key="id"
      :props="defaultProps"
      ref="tree"
    >
    </el-tree>
  </div>
</template>

<script>
export default {
  name: "Permission",
  data() {
    return {
      rid: "",
      perlist: [],
      perIds: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },
  methods: {
    loacData() {
      this.rid = this.$route.params.rid; //得到了url中传来的角色id
      this.$axios
        .get("/pers/" + this.rid)
        .then((res) => {
          this.perlist = res.data.data.perlist;
          this.perIds = res.data.data.perIds;
          alert(this.perIds);
          setTimeout(() => {
            //设置默认选中项
            this.locdcheck();
          }, 0);
        })
        .catch((error) => {});
    },
    locdcheck() {
      // alert("hahah")
      //checkedNodes1:角色对应的权限id
      for (var cid of this.perIds) {
        //根据key(id)获得树上的每一个节点,记得树上要设置node-key
        var treeNode = this.$refs.tree.getNode(cid);
        //判断树的节点如果是叶子节点
        if (treeNode.isLeaf) {
          //选中节点
          this.$refs.tree.setChecked(treeNode, true);
        }
      }
      console.log(this.$refs.tree.getNode(1).data.children.length);
    },
    savePers() {
      //获得选中的树节点的id
      var ids = this.$refs.tree.getCheckedKeys();
      //获得半选中状态的树节点的id
      var halfIds = this.$refs.tree.getHalfCheckedKeys();
      //将两个数组中的元素连接起来，放到一个数组中
      for (var halfid of halfIds) {
        ids.push(halfid);
      }
      this.$axios.post("/pers/updper",{
          rid:this.rid,
          perIds:ids
      })
      .then(res=>{
          this.perIds=[];
          alert(res.data.message);
          this.$router.push("/role");
      }).catch(error=>{

      })
    },
  },
  mounted() {
    this.loacData();
  }
};
</script>
